import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';

class LiveCommentDetectionPage extends StatefulWidget {
  const LiveCommentDetectionPage({Key? key}) : super(key: key);

  @override
  State<LiveCommentDetectionPage> createState() => _LiveCommentDetectionPageState();
}

class _LiveCommentDetectionPageState extends State<LiveCommentDetectionPage> {
  final TextEditingController _roomIdController = TextEditingController();
  InAppWebViewController? _controller;
  String _status = '等待输入直播间ID';
  final List<String> _logs = [];
  bool _isWebViewLoaded = false;
  String _currentRoomUrl = '';
  static const String _roomIdKey = 'saved_room_id';
  bool _isLogPanelVisible = true;
  final Set<String> _sentMessages = {}; // 用于去重的消息集合
  Timer? _heartbeatTimer; // 心跳定时器
  DateTime? _lastMessageTime; // 最后收到消息的时间
  
  @override
  void initState() {
    super.initState();
    _loadSavedRoomId();
  }
  
  Future<void> _loadSavedRoomId() async {
    final prefs = await SharedPreferences.getInstance();
    final savedRoomId = prefs.getString(_roomIdKey);
    if (savedRoomId != null && savedRoomId.isNotEmpty) {
      setState(() {
        _roomIdController.text = savedRoomId;
        _logs.add('加载上次保存的直播间ID: $savedRoomId');
      });
    }
  }
  
  Future<void> _saveRoomId(String roomId) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString(_roomIdKey, roomId);
    setState(() {
      _logs.add('直播间ID已保存: $roomId');
    });
  }

  void _loadLiveRoom() async {
    final roomId = _roomIdController.text.trim();
    if (roomId.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('请输入直播间ID')),
      );
      return;
    }
    
    // 保存roomId
    await _saveRoomId(roomId);
    
    final url = 'https://live.douyin.com/$roomId';
    print('[弹幕检测] 准备加载URL: $url');

    setState(() {
      _status = '正在进入直播间...';
      _logs.clear();
      _logs.add('开始进入直播间: $roomId');
      _logs.add('URL: $url');
      _currentRoomUrl = url;
      _isWebViewLoaded = true;
      _sentMessages.clear(); // 清空去重缓存
    });

    // 如果WebView已经创建，直接加载新URL
    if (_controller != null) {
      _controller!.loadUrl(urlRequest: URLRequest(
        url: WebUri(url),
        headers: {
          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
          'Referer': 'https://live.douyin.com',
        },
      ));
    }
  }

  void _startHeartbeatCheck() {
    // 取消之前的定时器
    _heartbeatTimer?.cancel();
    
    // 每30秒检查一次
    _heartbeatTimer = Timer.periodic(const Duration(seconds: 30), (timer) {
      if (_controller == null) return;
      
      // 检查是否长时间没有收到消息
      if (_lastMessageTime != null) {
        final timeSinceLastMessage = DateTime.now().difference(_lastMessageTime!);
        if (timeSinceLastMessage.inMinutes > 2) {
          setState(() {
            _logs.add('[系统] 检测到长时间无消息，尝试重新注入脚本...');
          });
          _startBarrageDetection();
        }
      }
      
      // 发送心跳检查
      _controller!.evaluateJavascript(source: '''
        (function() {
          if (window._commentCheckInterval) {
            console.log('监测脚本运行正常');
            return true;
          } else {
            console.log('监测脚本未运行，需要重新注入');
            return false;
          }
        })();
      ''').then((result) {
        if (result != true) {
          setState(() {
            _logs.add('[系统] 监测脚本已停止，重新注入...');
          });
          _startBarrageDetection();
        }
      });
    });
  }

  void _startBarrageDetection() {
    if (_controller == null) return;
    
    _controller!.evaluateJavascript(source: '''
      (function() {
        console.log('开始监测弹幕系统...');
        
        // 简化的消息解析器
        function parseDouyinChatMessages() {
          const messages = document.querySelectorAll('.webcast-chatroom___item');
          const parsedMessages = [];
          
          messages.forEach((message, index) => {
            const innerText = message.innerText?.trim() || '';
            
            if (innerText.includes('：')) {
              // 这是评论消息
              const colonIndex = innerText.indexOf('：');
              let username = innerText.substring(0, colonIndex).trim();
              
              // 处理用户名中的换行符
              if (username.includes('\\n')) {
                const usernameParts = username.split('\\n');
                if (usernameParts.length >= 2) {
                  username = usernameParts[1].trim();
                }
              }
              
              let content = innerText.substring(colonIndex + 1).trim();
              
              // 始终尝试获取图片的alt属性（处理文字+表情的情况）
              const imgs = message.querySelectorAll('img[alt]');
              const altTexts = [];
              imgs.forEach(img => {
                const alt = img.getAttribute('alt');
                if (alt && alt.trim()) {
                  altTexts.push(alt);
                }
              });
              
              // 如果有表情，添加到内容中
              if (altTexts.length > 0) {
                const emojiText = '[表情] ' + altTexts.join(' ');
                content = content ? content + ' ' + emojiText : emojiText;
              }
              
              if (username && content) {
                parsedMessages.push({
                  type: 'comment',
                  username: username,
                  content: content,
                  index: index,
                  fullText: innerText
                });
              }
            } else if (innerText.includes('来了')) {
              // 这是进入直播间消息
              const username = innerText.replace('来了', '').trim();
              
              parsedMessages.push({
                type: 'user_enter',
                username: username,
                content: innerText,
                index: index,
                fullText: innerText
              });
            }
          });
          
          return parsedMessages;
        }
        
        // 定期检查新消息
        let lastMessageCount = 0;
        let errorCount = 0;
        const checkInterval = setInterval(function() {
          try {
            // 检查页面是否还存在聊天室元素
            const chatroom = document.querySelector('.webcast-chatroom');
            if (!chatroom) {
              console.log('聊天室元素不存在，等待重新加载...');
              return;
            }
            
            const messages = parseDouyinChatMessages();
            
            // 调试：每10秒输出一次解析到的消息数量
            if (Date.now() % 10000 < 1000) {
              console.log('解析到消息数量:', messages.length);
            }
            
            // 发送所有消息（去重在Dart端处理）
            messages.forEach(msg => {
              try {
                if (msg.type === 'comment') {
                  window.flutter_inappwebview.callHandler('onChatMessage', 
                    JSON.stringify({
                      type: 'comment',
                      username: msg.username,
                      content: msg.content
                    })
                  );
                } else if (msg.type === 'user_enter') {
                  window.flutter_inappwebview.callHandler('onUserEnter', 
                    JSON.stringify({
                      type: 'user_enter',
                      content: msg.content,
                      username: msg.username
                    })
                  );
                }
              } catch(sendError) {
                console.error('发送消息错误:', sendError);
              }
            });
            
            // 重置错误计数
            errorCount = 0;
          } catch(e) {
            console.error('解析消息错误:', e);
            errorCount++;
            
            // 如果连续错误超过10次，尝试重新初始化
            if (errorCount > 10) {
              console.log('错误次数过多，尝试重新初始化...');
              errorCount = 0;
              lastMessageCount = 0;
            }
          }
        }, 1000); // 每秒检查一次
        
        // 保存定时器引用，以便页面卸载时清理
        window._commentCheckInterval = checkInterval;
        
        // 监听弹幕消息（保留原有的事件监听作为备用）
        if (window.webcastEventBus) {
          window.webcastEventBus.on('chatMessage', function(event) {
            window.flutter_inappwebview.callHandler('onChatMessage', JSON.stringify(event));
          });
          console.log('弹幕监听器已安装');
        }
        
        // 监听礼物消息
        if (window.webcastEventBus) {
          window.webcastEventBus.on('giftMessage', function(event) {
            window.flutter_inappwebview.callHandler('onGiftMessage', JSON.stringify(event));
          });
        }
        
        // 定期检查直播间状态
        setInterval(function() {
          try {
            var roomInfo = document.querySelector('.room-title');
            if (roomInfo) {
              window.flutter_inappwebview.callHandler('onRoomInfo', roomInfo.innerText);
            }
          } catch(e) {
            console.error('检查直播间状态错误:', e);
          }
        }, 5000);
      })();
    ''');
    
    // 添加JavaScript处理器
    _controller!.addJavaScriptHandler(
      handlerName: 'onChatMessage',
      callback: (args) {
        if (mounted && args.isNotEmpty) {
          try {
            // 尝试解析JSON格式的消息
            final messageData = args[0];
            if (messageData is String && messageData.contains('"type":"comment"')) {
              try {
                // 使用正则表达式提取username和content
                final usernameMatch = RegExp(r'"username"\s*:\s*"([^"]+)"').firstMatch(messageData);
                final contentMatch = RegExp(r'"content"\s*:\s*"([^"]+)"').firstMatch(messageData);
                
                if (usernameMatch != null && contentMatch != null) {
                  String username = usernameMatch.group(1) ?? '';
                  String content = contentMatch.group(1) ?? '';
                  
                  
                  if (username.isNotEmpty && content.isNotEmpty) {
                    // 创建消息唯一标识用于去重
                    final messageKey = 'comment|$username|$content';
                    
                    if (!_sentMessages.contains(messageKey)) {
                      _sentMessages.add(messageKey);
                      _lastMessageTime = DateTime.now(); // 更新最后消息时间
                      
                      setState(() {
                        _logs.add('[弹幕] $username: $content');
                      });
                      
                      // 限制缓存大小
                      if (_sentMessages.length > 1000) {
                        _sentMessages.remove(_sentMessages.first);
                      }
                    }
                  }
                }
              } catch (e) {
                print('解析评论消息错误: $e');
              }
            } else {
              setState(() {
                _logs.add('[弹幕] ${args[0].toString()}'.substring(0, 100));
              });
            }
          } catch (e) {
            setState(() {
              _logs.add('[弹幕] ${args[0].toString()}'.substring(0, 100));
            });
          }
        }
      },
    );
    
    _controller!.addJavaScriptHandler(
      handlerName: 'onUserEnter',
      callback: (args) {
        if (mounted && args.isNotEmpty) {
          try {
            final messageData = args[0];
            if (messageData is String && messageData.contains('"type":"user_enter"')) {
              final parsed = messageData.replaceAll(RegExp(r'[{}"]'), '');
              final parts = parsed.split(',');
              String content = '';
              
              for (var part in parts) {
                if (part.contains('content:')) {
                  content = part.substring(part.indexOf(':') + 1).trim();
                  break;
                }
              }
              
              if (content.isNotEmpty) {
                // 提取用户名并显示
                String displayText = content;
                String username = '用户';
                
                if (content.contains('来了')) {
                  username = content.split('来了')[0].trim();
                  // 处理用户名中的换行符
                  if (username.contains('\n')) {
                    final usernameParts = username.split('\n');
                    if (usernameParts.length >= 2) {
                      username = usernameParts[1].trim();
                    }
                  }
                  displayText = '$username 进来了';
                } else if (content.contains('欢迎') && content.contains('来到')) {
                  final match = RegExp(r'欢迎(.+?)来到').firstMatch(content);
                  if (match != null) {
                    username = match.group(1)?.trim() ?? '用户';
                    // 处理用户名中的换行符
                    if (username.contains('\n')) {
                      final usernameParts = username.split('\n');
                      if (usernameParts.length >= 2) {
                        username = usernameParts[1].trim();
                      }
                    }
                    displayText = '$username 进来了';
                  }
                }
                
                // 创建消息唯一标识用于去重
                final messageKey = 'enter|$username';
                
                if (!_sentMessages.contains(messageKey)) {
                  _sentMessages.add(messageKey);
                  _lastMessageTime = DateTime.now(); // 更新最后消息时间
                  
                  setState(() {
                    _logs.add('[进入] $displayText');
                  });
                  
                  // 限制缓存大小
                  if (_sentMessages.length > 1000) {
                    _sentMessages.remove(_sentMessages.first);
                  }
                }
              }
            } else {
              setState(() {
                _logs.add('[进入] ${args[0].toString()}'.substring(0, 100));
              });
            }
          } catch (e) {
            setState(() {
              _logs.add('[进入] ${args[0].toString()}'.substring(0, 100));
            });
          }
        }
      },
    );
    
    _controller!.addJavaScriptHandler(
      handlerName: 'onGiftMessage',
      callback: (args) {
        if (mounted) {
          setState(() {
            _logs.add('[礼物] ${args.isNotEmpty ? args[0] : ""}'.substring(0, 100));
          });
        }
      },
    );
    
    _controller!.addJavaScriptHandler(
      handlerName: 'onRoomInfo',
      callback: (args) {
        if (mounted && args.isNotEmpty) {
          setState(() {
            _status = '监测中 - ${args[0]}';
          });
        }
      },
    );
  }

  @override
  void dispose() {
    _roomIdController.dispose();
    _heartbeatTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
      children: [
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _roomIdController,
                    decoration: const InputDecoration(
                      labelText: '直播间ID',
                      hintText: '请输入抖音直播间ID',
                      border: OutlineInputBorder(),
                      prefixIcon: Icon(Icons.live_tv),
                    ),
                    keyboardType: TextInputType.number,
                  ),
                ),
                const SizedBox(width: 10),
                ElevatedButton(
                  onPressed: _loadLiveRoom,
                  style: ElevatedButton.styleFrom(
                    padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
                  ),
                  child: const Text('进入直播间'),
                ),
              ],
            ),
          ),
          Expanded(
            child: Stack(
              children: [
                if (_isWebViewLoaded && _currentRoomUrl.isNotEmpty)
                  InAppWebView(
                      initialUrlRequest: URLRequest(
                        url: WebUri(_currentRoomUrl),
                        headers: {
                          'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                          'Referer': 'https://live.douyin.com',
                        },
                      ),
                      initialOptions: InAppWebViewGroupOptions(
                        crossPlatform: InAppWebViewOptions(
                          userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
                          javaScriptEnabled: true,
                          supportZoom: true,
                          useOnLoadResource: true,
                          preferredContentMode: UserPreferredContentMode.DESKTOP,
                          minimumFontSize: 1,
                        ),
                        android: AndroidInAppWebViewOptions(
                          useHybridComposition: true,
                          supportMultipleWindows: true,
                          domStorageEnabled: true,
                          databaseEnabled: true,
                          useWideViewPort: true,
                          loadWithOverviewMode: true,
                          builtInZoomControls: true,
                          displayZoomControls: false,
                          initialScale: 100,
                          textZoom: 100,
                        ),
                        ios: IOSInAppWebViewOptions(
                          allowsInlineMediaPlayback: true,
                        ),
                      ),
                      onWebViewCreated: (controller) {
                        _controller = controller;
                        print('[弹幕检测] WebView已创建');
                        setState(() {
                          _logs.add('[系统] WebView控制器已创建');
                        });
                      },
                      onLoadStart: (controller, url) {
                        print('[弹幕检测] 开始加载: $url');
                        setState(() {
                          _status = '正在进入直播间...';
                          _logs.add('开始加载页面: $url');
                        });
                      },
                      onLoadStop: (controller, url) async {
                        print('[弹幕检测] 加载完成: $url');
                        setState(() {
                          _status = '正在监测弹幕...';
                          _logs.add('页面加载完成: $url');
                        });
                        
                        // Force desktop viewport
                        await controller.evaluateJavascript(source: '''
                          var viewport = document.querySelector('meta[name="viewport"]');
                          if (viewport) {
                            viewport.content = 'width=1280, initial-scale=1.0';
                          } else {
                            var meta = document.createElement('meta');
                            meta.name = 'viewport';
                            meta.content = 'width=1280, initial-scale=1.0';
                            document.getElementsByTagName('head')[0].appendChild(meta);
                          }
                          
                          // Remove any mobile-specific styles
                          document.documentElement.style.minWidth = '1280px';
                          document.body.style.minWidth = '1280px';
                        ''');
                        
                        _startBarrageDetection();
                        _startHeartbeatCheck();
                      },
                      onProgressChanged: (controller, progress) {
                        if (progress % 20 == 0) {
                          print('[弹幕检测] 加载进度: $progress%');
                        }
                        setState(() {
                          _status = '加载中... $progress%';
                        });
                      },
                      onReceivedError: (controller, request, error) {
                        print('[弹幕检测] 加载错误: ${error.type} - ${error.description}');
                        setState(() {
                          _status = '加载错误';
                          _logs.add('错误: ${error.type} - ${error.description}');
                        });
                      },
                      onReceivedHttpError: (controller, request, response) {
                        print('[弹幕检测] HTTP错误: ${response.statusCode}');
                        setState(() {
                          _logs.add('HTTP错误: ${response.statusCode}');
                        });
                      },
                      onConsoleMessage: (controller, consoleMessage) {
                        if (mounted) {
                          setState(() {
                            // _logs.add('[Console] ${consoleMessage.message}');
                          });
                        }
                      },
                      shouldOverrideUrlLoading: (controller, navigationAction) async {
                        // Ensure all navigation uses desktop mode
                        return NavigationActionPolicy.ALLOW;
                      },
                    )
                else
                  const Center(
                    child: Text('请输入直播间ID开始检测'),
                  ),
                Positioned(
                  top: 10,
                  left: 10,
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    decoration: BoxDecoration(
                      color: Colors.black87,
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withOpacity(0.3),
                          blurRadius: 6,
                          offset: const Offset(0, 3),
                        ),
                      ],
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 8,
                          height: 8,
                          decoration: BoxDecoration(
                            color: _status.contains('错误') ? Colors.red : 
                                   _status.contains('监测') ? Colors.green : 
                                   Colors.orange,
                            shape: BoxShape.circle,
                          ),
                        ),
                        const SizedBox(width: 8),
                        Text(
                          _status,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            fontWeight: FontWeight.w500,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                AnimatedPositioned(
                  duration: const Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                  bottom: _isLogPanelVisible ? 0 : -150,
                  left: 0,
                  right: 0,
                  child: Container(
                    height: 150,
                    color: Colors.black.withOpacity(0.8),
                    child: Column(
                      children: [
                        Container(
                          padding: const EdgeInsets.all(8),
                          decoration: const BoxDecoration(
                            border: Border(
                              bottom: BorderSide(color: Colors.grey),
                            ),
                          ),
                          child: Row(
                            children: [
                              const Icon(Icons.terminal, color: Colors.white, size: 16),
                              const SizedBox(width: 8),
                              const Text(
                                '监测日志',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              const Spacer(),
                              TextButton(
                                onPressed: () {
                                  setState(() {
                                    _logs.clear();
                                  });
                                },
                                child: const Text(
                                  '清空',
                                  style: TextStyle(color: Colors.grey, fontSize: 12),
                                ),
                              ),
                            ],
                          ),
                        ),
                        Expanded(
                          child: ListView.builder(
                            padding: const EdgeInsets.all(8),
                            itemCount: _logs.length,
                            itemBuilder: (context, index) {
                              return Text(
                                _logs[index],
                                style: const TextStyle(
                                  color: Colors.greenAccent,
                                  fontSize: 12,
                                  fontFamily: 'monospace',
                                ),
                              );
                            },
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
                // 隐藏/显示日志面板的悬浮按钮
                Positioned(
                  bottom: _isLogPanelVisible ? 160 : 10,
                  right: 10,
                  child: AnimatedContainer(
                    duration: const Duration(milliseconds: 300),
                    child: FloatingActionButton(
                      mini: true,
                      backgroundColor: Colors.black87,
                      onPressed: () {
                        setState(() {
                          _isLogPanelVisible = !_isLogPanelVisible;
                        });
                      },
                      child: AnimatedRotation(
                        turns: _isLogPanelVisible ? 0.5 : 0,
                        duration: const Duration(milliseconds: 300),
                        child: const Icon(Icons.keyboard_arrow_down, color: Colors.white),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
      ],
    ),
    );
  }
}